from pptx2html import convert
from pptx import Presentation


html = """
 <!DOCTYPE html>
 <html>
 <head>
 <meta charset="utf-8">
 <title>TroyOcr</title>
 <style>table, th, td {{border: 1px solid black;}}</style>
 <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=TeX-MML-AM_CHTML"></script>
 </head>
 <body>
 {html_partial}
 </body>
 </html>     
 """

# output = convert("/home/demut/datasets/doc_tests/demo2.pptx")

from io import BytesIO
from PIL import Image
from pptx2html import parse_page, outputter


def convert_image(im_bytes):
    bytes_stream = BytesIO(im_bytes)
    image = Image.open(bytes_stream)
    try:
        image.save("/home/demut/trash/statics/test.jpg")
    except:
        image.save("/home/demut/trash/statics/test.jpg", "PNG")

    return "./trash/statics/test.jpg"


# output = convert("/home/demut/projects/mytests/ragflow/hl/proj/doc_test/test1.pptx", convert_image=convert_image)

pptx_loader = Presentation("/home/demut/projects/mytests/ragflow/hl/proj/doc_test/demo2.pptx")


# for i in range(len(pptx_loader.slides)):
#     slide = pptx_loader.slides[i]
#     print("slide index: ", i)
#     for shape in slide.shapes:
#         # print(shape)
#         # if hasattr(shape, "text"):
#         #     text_frame = shape.text_frame
#         #     text = text_frame.text

#         if shape.has_text_frame:
#             text_frame = shape.text_frame
#             print(text_frame.text)

#     if i == 1:
#         break
#     # str = i.shapes.title
#     # if str:
#     #     print(str.text)
#     # else:
#     #     print("null")


output_html = ""
out = outputter.html_outputter(None)
for page_idx in range(len(pptx_loader.slides)):  # 后面可支持离散的页码
    # print(page_idx)
    if page_idx != 1:
        continue

    parse_page(pptx_loader.slides[page_idx], out, page_idx, convert_image=convert_image)

out.close()

output_html = out.get_output()


with open("test_.html", "w") as file:
    file.write(html.format(html_partial=output_html))
